<script>
import ClassesApi from "../api/classes";
import StudentApi from "../api/student";

export default {
  data() {
    return {
      dataList: [], //数据集合
      classesList: [], //班级集合
      classesId: null, //当前选中班级
      addDialogVisible: false, //新增数据对话框控制
      addStudent: {
        number: "",
        name: "",
        age: -1,
        gender: -1,
        classesId: null
      }, // 新增数据的格式
      editDialogVisible: false, //编辑数据对话框控制
      editStudent: {
        id: 0,
        number: "",
        name: "",
        age: -1,
        gender: -1,
        classesId: null
      }, // 编辑数据的格式
      deleteStudent: {
        id: 0,
        number: "",
        name: "",
        age: -1,
        gender: -1,
        classesId: null
      }, // 删除数据的格式
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  methods: {
    async getList() {
      //TODO:网络访问错误的处理
      let api = new StudentApi();
      // this.dataList = await api.getList();
      this.dataList = await api.getList(this.currentPage, this.pageSize);
      console.log(this.dataList);
    },
    async getCount() {
      let api = new StudentApi();
      this.total = await api.getCount();
      console.log(this.total);
    },
    async getData() {
      await this.getCount();
      await this.getList();
    },
    handleCurrentChange() {
      console.log(this.currentPage);
      this.getList();
    },
    indexMethod(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    showAddDialog() {
      this.addDialogVisible = true;
    },
    async addSubmit() {
      if (!this.$refs.formAdd) return;
      let formEl = this.$refs.formAdd;
      await formEl.validate(async (valid) => {
        if (valid) {
          let api = new StudentApi();
          await api.add(this.addStudent);
          formEl.resetFields(); //清空表单
          this.addDialogVisible = false; //关闭对话框
          this.getData(); //刷新数据列表
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    addReset() {
      if (!this.$refs.formAdd) return;
      let formEl = this.$refs.formAdd;
      formEl.resetFields(); //重置表单
      this.addDialogVisible = false;
    },
    showEditDialog(index, row) {
      console.log(index, row);
      this.editDialogVisible = true;
      this.editStudent = row; //需要编辑的数据行
    },
    async editSubmit() {
      if (!this.$refs.formEdit) return;
      let formEl = this.$refs.formEdit;
      await formEl.validate(async (valid) => {
        if (valid) {
          let api = new StudentApi();
          await api.edit(this.editStudent);
          formEl.resetFields(); //清空表单
          this.editDialogVisible = false; //关闭对话框
          this.getData(); //刷新数据列表
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    editReset() {
      if (!this.$refs.formEdit) return;
      let formEl = this.$refs.formEdit;
      formEl.resetFields(); //重置表单
      this.editDialogVisible = false;
    },
    showDeleteDialog(index, row) {
      console.log(index, row);
      // eslint-disable-next-line no-undef
      ElMessageBox.confirm("确认删除吗？", "删除记录", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.deleteStudent = row;
          let api = new StudentApi();
          await api.delete(this.deleteStudent.id);
          this.getData();
          // eslint-disable-next-line no-undef
          ElMessage({
            type: "success",
            message: "记录已删除"
          });
        })
        .catch(() => {
          // eslint-disable-next-line no-undef
          ElMessage({
            type: "info",
            message: "删除已终止"
          });
        });
    },
    async getListByClassId() {
      let api = new StudentApi();
      this.dataList = await api.getListByClassesId(this.classesId, this.currentPage, this.pageSize);
      this.total = await api.getCountByClassesId(this.classesId);
      console.log(this.dataList);
    },
    async getClassesList() {
      let api = new ClassesApi();
      this.classesList = await api.getList();
      console.log(this.classesList);
    },
    genderName(row) {
      if (row.gender === 1) return "男";
      if (row.gender === 2) return "女";
    },
    classesName(row) {
      let value = this.classesList.filter((item) => item.id === row.classesId);
      return `${value[0].name} / ${value[0].department}`;
    }
  },
  mounted() {
    // this.getList();
    this.getData();
    this.getClassesList();
  }
};
</script>

<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/manager/student' }">学生管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider />
    <!-- 功能区 -->
    <el-row class="row-bg" justify="space-between">
      <el-col :span="4">
        <h3>学生管理</h3>
      </el-col>
      <el-col :span="8">
        <el-space wrap>
          <el-select
            v-model="classesId"
            placeholder="按班级显示"
            filterable
            @change="getListByClassId">
            <el-option
              v-for="item in classesList"
              :key="item.id"
              :label="item.name + ' / ' + item.department"
              :value="item.id" />
          </el-select>
          <el-button type="primary" @click="showAddDialog">新增</el-button>
        </el-space>
      </el-col>
    </el-row>
    <!-- 数据列表 -->
    <el-table :data="dataList" style="width: 100%" height="60vh" empty-text="暂无数据" border>
      <el-table-column type="index" label="序号" width="100" align="center" :index="indexMethod" />
      <el-table-column prop="number" label="学号" align="center" />
      <el-table-column prop="name" label="姓名" align="center" />
      <el-table-column prop="gender" label="性别" align="center" :formatter="genderName" />
      <el-table-column prop="age" label="年龄" align="center" />
      <el-table-column prop="classesId" label="班级" align="center" :formatter="classesName" />
      <el-table-column fixed="right" width="200">
        <template #default="scope">
          <el-button type="warning" size="small" @click="showEditDialog(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="showDeleteDialog(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-if="total > 0"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      background
      layout="prev, pager, next" />
    <!-- 新增数据 -->
    <el-dialog v-model="addDialogVisible" title="新增">
      <el-form :model="addStudent" label-width="120px" ref="formAdd">
        <el-form-item
          label="学号"
          prop="number"
          :rules="[{ required: true, message: '学号为必填项' }]">
          <el-input v-model="addStudent.number" placeholder="输入学号" />
        </el-form-item>

        <el-form-item
          label="姓名"
          prop="name"
          :rules="[{ required: true, message: '姓名为必填项' }]">
          <el-input v-model="addStudent.name" placeholder="输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="addStudent.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="addStudent.age" :min="10" :max="60" placeholder="输入年龄" />
        </el-form-item>

        <el-form-item label="班级" prop="classesId">
          <el-select v-model="addStudent.classesId" placeholder="选择班级">
            <el-option
              v-for="item in classesList"
              :key="item.id"
              :label="item.name + ' / ' + item.department"
              :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="addReset">取消</el-button>
          <el-button type="primary" @click="addSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑数据 -->

    <el-dialog v-model="editDialogVisible" title="编辑">
      <el-form :model="editStudent" label-width="120px" ref="formEdit">
        <el-form-item
          label="学号"
          prop="number"
          :rules="[{ required: true, message: '学号为必填项' }]">
          <el-input v-model="editStudent.number" placeholder="输入学号" />
        </el-form-item>

        <el-form-item
          label="姓名"
          prop="name"
          :rules="[{ required: true, message: '姓名为必填项' }]">
          <el-input v-model="editStudent.name" placeholder="输入姓名" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editStudent.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="editStudent.age" :min="10" :max="60" placeholder="输入年龄" />
        </el-form-item>

        <el-form-item label="班级" prop="classesId">
          <el-select v-model="editStudent.classesId" placeholder="选择班级">
            <el-option
              v-for="item in classesList"
              :key="item.id"
              :label="item.name + ' / ' + item.department"
              :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="editReset">取消</el-button>
          <el-button type="primary" @click="editSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.el-row {
  margin-bottom: 16px;
}

.el-table {
  margin-bottom: 16px;
}
</style>
